using System;
using System.IO;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared.SharedTypes;
using OST.Persistence;
using OST.Shared;

namespace OST.Commands
{
    using Extensions;

    /// <summary>
    /// returns the content of the 'index.htm' file in removable-storage
    /// </summary>
    public class WebClientGETCommand : mfRcfCommand
    {
        #region Consts
        private const string C_STR_INDEX_FILE_NAME = "index.htm";
        #endregion

        #region CTOR

        public WebClientGETCommand(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
            ContentTypeOut = "text/html";
        }

        #endregion

        #region Properties

        /// <summary>
        /// wrapper-property 4 logging
        /// </summary>
        private ILoggerAppender Logger
        {
            get
            {
                return mfLogger.mfLogger.Instance;
            }
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            try
            {
                if (!RemoveableMediaStorageProvider.Instance.IsStorageConntected)
                    throw new OSTException("no storage loaded");

                var storage = RemoveableMediaStorageProvider.Instance.RootDirectory;

                var indexFilePath = Path.Combine(storage, C_STR_INDEX_FILE_NAME);

                var indexFileStream = new StreamReader(indexFilePath);

                httpContext.Response.ContentType = ContentTypeOut;
                httpContext.Response.StatusCode = enumHttpStatusCode.OK;

                httpContext.Response.WriteBytes(indexFileStream.BaseStream.ReadAllBytes());

                httpContext.Response.Close();

                indexFileStream.Close();
                indexFileStream.Dispose();
                Logger.Debug(GetType() + " executed, " + Debug.GC(true) + " bytes free");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }
        #endregion
    }
}
